<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>企业职员管理系统 - 部门编辑</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500;700&display=swap" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Noto Sans SC', 'Segoe UI', 'Microsoft YaHei', sans-serif;
        }

        :root {
            --primary: #3498db;
            --secondary: #2ecc71;
            --dark: #2c3e50;
            --light: #f8f9fa;
            --gray: #7f8c8d;
            --border: #e0e0e0;
            --card-bg: rgba(255, 255, 255, 0.95);
            --shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
            --transition: all 0.3s ease;
            --error: #e74c3c;
            --success: #2ecc71;
        }

        body {
            display: flex;
            min-height: 100vh;
            background: linear-gradient(135deg, #f5f7fa, #e4e7eb);
            color: var(--dark);
        }

        .container {
            max-width: 1200px;
            width: 100%;
            margin: 40px auto;
            padding: 0 20px;
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 1px solid var(--border);
        }

        .header h1 {
            font-size: 1.8rem;
            font-weight: 700;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .back-btn {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 10px 20px;
            background: var(--light);
            color: var(--dark);
            border: 1px solid var(--border);
            border-radius: 8px;
            font-weight: 500;
            cursor: pointer;
            transition: var(--transition);
            text-decoration: none;
        }

        .back-btn:hover {
            background: var(--primary);
            color: white;
            border-color: var(--primary);
        }

        .edit-container {
            background: var(--card-bg);
            border-radius: 20px;
            box-shadow: var(--shadow);
            padding: 40px;
            transition: transform 0.4s, box-shadow 0.4s;
            position: relative;
            overflow: hidden;
        }

        .edit-container:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 45px rgba(0, 0, 0, 0.15);
        }

        .edit-container::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 5px;
            background: linear-gradient(90deg, var(--primary), var(--secondary), var(--primary));
            background-size: 200% 200%;
            animation: gradientBar 3s ease infinite;
        }

        @keyframes gradientBar {
            0% { background-position: 0% 50%; }
            50% { background-position: 100% 50%; }
            100% { background-position: 0% 50%; }
        }

        .form-header {
            text-align: center;
            margin-bottom: 30px;
        }

        .form-header i {
            font-size: 2.8rem;
            color: var(--dark);
            margin-bottom: 15px;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .form-header h2 {
            color: var(--dark);
            font-weight: 700;
            font-size: 1.8rem;
            margin: 5px 0;
        }

        .form-header p {
            color: var(--gray);
            font-size: 1.1rem;
            margin-top: 5px;
        }

        .form-group {
            margin-bottom: 25px;
        }

        .form-group label {
            display: block;
            margin-bottom: 10px;
            color: var(--dark);
            font-weight: 500;
            font-size: 1rem;
        }

        .input-icon {
            position: relative;
        }

        .input-icon i {
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--gray);
            font-size: 1.1rem;
        }

        input, select, textarea {
            width: 100%;
            padding: 14px 15px 14px 45px;
            border: 2px solid var(--border);
            border-radius: 10px;
            font-size: 16px;
            transition: all 0.3s;
            background: #fff;
        }

        textarea {
            min-height: 120px;
            resize: vertical;
        }

        input:focus, select:focus, textarea:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
        }

        .form-row {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
        }

        .form-row .form-group {
            flex: 1;
            margin-bottom: 0;
        }

        .submit-btn {
            display: inline-flex;
            align-items: center;
            gap: 10px;
            padding: 15px 30px;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 17px;
            font-weight: 600;
            cursor: pointer;
            transition: var(--transition);
            margin-top: 20px;
            box-shadow: 0 5px 15px rgba(52, 152, 219, 0.3);
        }

        .submit-btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 20px rgba(52, 152, 219, 0.4);
        }

        .submit-btn:active {
            transform: translateY(0);
        }

        .btn-group {
            display: flex;
            justify-content: flex-end;
            gap: 15px;
            margin-top: 30px;
        }

        .cancel-btn {
            display: inline-flex;
            align-items: center;
            gap: 10px;
            padding: 15px 30px;
            background: var(--light);
            color: var(--dark);
            border: 1px solid var(--border);
            border-radius: 10px;
            font-size: 17px;
            font-weight: 600;
            cursor: pointer;
            transition: var(--transition);
        }

        .cancel-btn:hover {
            background: #f1f1f1;
            border-color: var(--primary);
            color: var(--primary);
        }

        .notification {
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            background: #fff;
            padding: 15px 25px;
            border-radius: 8px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.15);
            display: flex;
            align-items: center;
            z-index: 1000;
            opacity: 0;
            transition: opacity 0.3s, top 0.3s;
            pointer-events: none;
            max-width: 500px;
            width: 90%;
        }

        .notification.show {
            top: 30px;
            opacity: 1;
        }

        .notification i {
            font-size: 24px;
            margin-right: 15px;
        }

        .notification.success i {
            color: var(--success);
        }

        .notification.error i {
            color: var(--error);
        }

        .notification .content {
            flex: 1;
        }

        .notification .title {
            font-weight: 600;
            font-size: 16px;
            margin-bottom: 3px;
        }

        .notification .message {
            font-size: 14px;
            color: #555;
        }

        @media (max-width: 768px) {
            .form-row {
                flex-direction: column;
                gap: 15px;
            }

            .edit-container {
                padding: 30px 20px;
            }

            .btn-group {
                flex-direction: column;
            }

            .submit-btn, .cancel-btn {
                width: 100%;
                justify-content: center;
            }
        }

        @media (max-width: 576px) {
            .header {
                flex-direction: column;
                align-items: flex-start;
                gap: 15px;
            }

            .header h1 {
                font-size: 1.5rem;
            }
        }
    </style>
</head>
<body>
    <!-- 通知组件 -->
    <div class="notification" id="notification">
        <i class="fas fa-check-circle"></i>
        <div class="content">
            <div class="title">部门信息已保存</div>
            <div class="message">部门信息已成功更新并保存</div>
        </div>
    </div>

    <div class="container">
        <div class="header">
            <button class="back-btn" onclick="window.location.href='/company/departmentManagement'">
                <i class="fas fa-arrow-left"></i> 返回列表
            </button>
        </div>

        <div class="edit-container">
            <div class="form-header">
                <i class="fas fa-sitemap"></i>
                <h2>部门信息编辑</h2>
                <p>修改并更新部门详细信息</p>
            </div>

            <form id="departmentForm">
                <input type="hidden" id="departmentId" name="id">
                <div class="form-row">
                    <div class="form-group">
                        <label for="departmentName">部门名称</label>
                        <div class="input-icon">
                            <i class="fas fa-signature"></i>
                            <input type="text"
                                   id="departmentName"
                                   name="departmentName"
                                   placeholder="请输入部门名称"
                                   value=""
                                   required>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="departmentParent">上级部门</label>
                        <div class="input-icon">
                            <i class="fas fa-user-tie"></i>
                            <!-- 上级部门 -->
                            <select id="departmentParent" name="departmentParent">
                                <option value=""></option>
                            </select>
                        </div>
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label for="manager">负责人</label>
                        <div class="input-icon">
                            <i class="fas fa-user-tie"></i>
                            <!-- 负责人 -->
                            <select id="manager" name="manager" required>
                                <option value=""></option>
                            </select>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="foundationDate">成立日期</label>
                        <div class="input-icon">
                            <i class="fas fa-calendar-alt"></i>
                            <input type="date"
                                   id="foundationDate"
                                   name="foundationDate"
                                   value=""
                                   required>
                        </div>
                    </div>
                </div>

                <div class="btn-group">
                    <button type="submit" class="submit-btn">
                        <i class="fas fa-save"></i> 保存更改
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script>
        let form;
        document.addEventListener('DOMContentLoaded', function () {
            const params = new URLSearchParams(window.location.search);
            form = document.getElementById('departmentForm');
            const submitBtn = document.querySelector('.submit-btn'); // 修复 submitBtn 引用

            const parentSelect = document.getElementById('departmentParent');
            const managerSelect = document.getElementById('manager');

            async function fetchData(url) {
                const response = await fetch(url);
                return await response.json();
            }

            function populateSelect(selectElement, data, labelKey = 'name', valueKey = 'id') {
                selectElement.innerHTML = '<option value="">选择</option>';
                data.forEach(item => {
                    const option = document.createElement('option');
                    option.value = item[valueKey];
                    option.textContent = item[labelKey];
                    selectElement.appendChild(option);
                });
            }

            Promise.all([
                fetchData('api/department/parents'),
                fetchData('api/department/managers')
            ]).then(([parents, managers]) => {
                // 填充下拉框
                populateSelect(parentSelect, parents);
                populateSelect(managerSelect, managers);

                // 强制等待下拉框渲染完成后再设置值
                setTimeout(() => {
                    if (params.has('id')) {
                        document.getElementById('departmentId').value = params.get('id');
                        document.getElementById('departmentName').value = params.get('name');

                        document.getElementById('departmentParent').value = params.get('parentId');
                        document.getElementById('manager').value = params.get('managerId');

                        document.getElementById('foundationDate').value = params.get('createTime');

                        form.setAttribute('data-mode', 'edit');
                        if (submitBtn) {
                            submitBtn.textContent = '更新部门';
                        }
                    } else {
                        form.reset();
                        form.setAttribute('data-mode', 'add');
                    }
                    console.log("Form Element:", form);
                }, 0.1); // 使用微任务延迟执行，确保 DOM 更新完成
            }).catch(err => {
                console.error('数据加载失败:', err);
                alert('无法加载下拉数据，请刷新页面重试。');
            });

        });

        // 显示通知
        function showNotification(type, title, message) {
            const notification = document.getElementById('notification');
            const icon = notification.querySelector('i');

            // 设置通知内容
            notification.querySelector('.title').textContent = title;
            notification.querySelector('.message').textContent = message;

            // 设置图标和颜色
            if (type === 'success') {
                icon.className = 'fas fa-check-circle';
                notification.className = 'notification success';
            } else {
                icon.className = 'fas fa-exclamation-circle';
                notification.className = 'notification error';
            }

            // 显示通知
            notification.classList.add('show');

            // 5秒后隐藏
            setTimeout(() => {
                notification.classList.remove('show');
            }, 5000);
        }

        // 表单验证和提交
        document.getElementById('departmentForm').addEventListener('submit', async function (e) {
            e.preventDefault();
            const mode = form.getAttribute('data-mode');
            const departmentId = document.getElementById('departmentId').value;

            // 收集表单数据
            const formData = {
                departmentName: document.getElementById('departmentName').value,
                parentId: parseInt(document.getElementById('departmentParent').value),
                managerId: parseInt(document.getElementById('manager').value),
                foundationDate: document.getElementById('foundationDate').value
            };

            let url, method;
            if (mode === 'edit' && departmentId) {
                url = `api/department/edit/${departmentId}`;
                method = 'PUT'; // 编辑用 PUT
            } else {
                url = 'api/department/add';
                method = 'POST'; // 新增用 POST
            }
            // 发送请求
            try {
                const submitBtn = document.querySelector('.submit-btn'); // 重新获取 submitBtn
                const originalHtml = submitBtn.innerHTML;
                submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 保存中...';
                submitBtn.disabled = true;

                const response = await fetch(url, {
                    method: method,
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(formData)
                });

                const result = await response.json();
                if (result.success) {
                    showNotification('success', '保存成功', '部门信息已成功更新');
                    setTimeout(() => window.location.href = '/company/departmentManagement', 1500);
                } else {
                    showNotification('error', '保存失败', result.message || '请稍后再试');
                }

                // 恢复按钮
                setTimeout(() => {
                    submitBtn.innerHTML = originalHtml;
                    submitBtn.disabled = false;
                }, 2000);

            } catch (err) {
                console.error('提交失败:', err);
                showNotification('error', '网络错误', '无法连接服务器，请检查网络');
            }
        });

        // 取消按钮功能
        const cancelBtn = document.querySelector('.cancel-btn');
        if (cancelBtn) {
            cancelBtn.addEventListener('click', function() {
                if (confirm('确定要取消编辑吗？所有更改将不会保存。')) {
                    window.location.href = '/company/departmentManagement'; // 替换为实际的列表页面
                }
            });
        }
    </script>
</body>
<!--111-->
</html>